package net.youpo.Market.UI.AppInfo;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Bean.ScreenshotBean;
import net.youpo.Market.Download.DownloadManager;
import net.youpo.Market.Download.Downloads;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.UI.StarView;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.GlobalVariables;
import net.youpo.Market.Util.Tools;
import net.youpo.Market.db.AppInfoTable;
import net.youpo.Market.db.MarketDatabase;
import net.youpo.Market.db.MessageTable;
import net.youpo.Market.db.ScreenshotTable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MessageAppInfoActivity extends Activity {
	private final String APPINFO_LOGTIME = "appinfo_logtime";
	private final int REFRESH_ICON = 556;
	private final int REFRESH_LIST = 516;
	private final int REFRESH_TIME = 200;// 刷新间隔
	private final String REQS_CONFIG = "App/info/";
	private final int LOADING_DONE = 0;
	private boolean mDownloadFlag = true;
	private AppInfoBean mAppBean = new AppInfoBean();
	private DownloadManager mDownloadManager;
	private ProgressDialog mLoadingDialog;
	private ImageView mIconIM;
	private TextView mAppNameTV;
	private TextView mAppDownloadCountTV;
	private StarView mAppSV;
	private ImageView mAppImageView;
	private TextView mAppVersion;
	private TextView mAppSize;
	private TextView mAppDesc;
	private TextView mAppLan;
	private TextView mAppAutho;
	private Button mDownloadBtn;
	private Button mFavoritesBtn;
	private BlockingQueue<Runnable> mBlockingQueue = new LinkedBlockingQueue<Runnable>();// 创建线程队列
	private ThreadPoolExecutor mExecutor = new ThreadPoolExecutor(1, 10, 30,
			TimeUnit.SECONDS, mBlockingQueue);// 创建线程池,线程大小1,最大池大小10,线程持续时间30,持续时间单位s，线程队列

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mAppBean.APP_ID = getIntent().getStringExtra(ConstantsTable.KEY_APPID);
		mAppBean.IS_RECOMMEND = true;
		mAppBean.RECOMMEND_ID = getIntent().getStringExtra(
				ConstantsTable.RECOMMEND_ID);
		mLoadingDialog = ProgressDialog.show(this, "", "正在加载. 请等待...", true);
		setContentView(R.layout.message_info);
		this.mDownloadManager = new DownloadManager(this);
		initUI();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// 从数据库中查询所需要的数据，如果没有数据就从网络中获取
				int resultCount = getDataFromDB();
				Log.d("H3c", "db:" + resultCount + "-" + mAppBean.APP_DESC);
				if (resultCount == 0) {
					Log.d("H3c", "net");
					SharedPreferences sPreferences = PreferenceManager
							.getDefaultSharedPreferences(MessageAppInfoActivity.this);
					getDataFromNetwork(sPreferences);
				}
				mHandler.sendEmptyMessage(LOADING_DONE);
			}
		}).start();
	}

	private void initUI() {
		mIconIM = (ImageView) findViewById(R.id.appinfo_icon);
		mAppNameTV = (TextView) findViewById(R.id.appinfo_Name);
		mAppDownloadCountTV = (TextView) findViewById(R.id.appinfo_downloadCount);
		mAppSV = (StarView) findViewById(R.id.appinfo_starView);
		mAppVersion = (TextView) findViewById(R.id.appinfo_version_tv);
		mAppSize = (TextView) findViewById(R.id.appinfo_size_tv);
		mAppLan = (TextView) findViewById(R.id.appinfo_lan_tv);
		mAppAutho = (TextView) findViewById(R.id.appinfo_autho_tv);
		mAppDesc = (TextView) findViewById(R.id.appinfo_desc_tv);
		mDownloadBtn = (Button) findViewById(R.id.appinfo_download_btn);
		mFavoritesBtn = (Button) findViewById(R.id.appinfo_delete_btn);
		mAppImageView = (ImageView) findViewById(R.id.appinfo_im);

		mDownloadBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (mDownloadFlag) {
					Toast.makeText(MessageAppInfoActivity.this, "开始下载",
							Toast.LENGTH_SHORT).show();
					mDownloadManager.insertDownload(mAppBean,
							Downloads.TYPE_DOWNLOAD);
					mDownloadFlag = false;
				} else {
					Toast.makeText(MessageAppInfoActivity.this, "已经开始下载,请耐心等候",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		mFavoritesBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (mDownloadFlag) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							MessageAppInfoActivity.this);
					builder.setMessage(
							"您尚未下载任何推荐软件，确定要关闭该窗口吗？选择“免费下载”安装使用任意一款推荐应用后，如果选择取消，近期将不推送任务软件")
							.setTitle("温馨提示")
							.setCancelable(false)
							.setPositiveButton("立即免费下载",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											Toast.makeText(
													MessageAppInfoActivity.this,
													"开始下载", Toast.LENGTH_SHORT)
													.show();
											mDownloadManager.insertDownload(
													mAppBean,
													Downloads.TYPE_DOWNLOAD);
											mDownloadFlag = false;
										}
									})
							.setNegativeButton("关闭",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											Integer notificationId = GlobalVariables.MESSAGE_MAP
													.get(mAppBean.RECOMMEND_ID);
											if (notificationId != null) {
												NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
												notificationManager
														.cancel(notificationId);
												GlobalVariables.MESSAGE_MAP
														.remove(mAppBean.APP_NAME);// 清除消息
											}
											MessageAppInfoActivity.this
													.finish();
										}
									});
					builder.create();
					builder.show();
				} else {
					Integer notificationId = GlobalVariables.MESSAGE_MAP
							.get(mAppBean.RECOMMEND_ID);
					if (notificationId != null) {
						NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
						notificationManager.cancel(notificationId);
						GlobalVariables.MESSAGE_MAP.remove(mAppBean.APP_NAME);// 清除消息
					}
					MessageAppInfoActivity.this.finish();
				}
			}
		});
	}

	private int getDataFromDB() {
		int count = 0;// 返回值个数
		// 获得数据库对象
		SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
		// 查询表中的数据
		Cursor cursor = marketDB.query(MessageTable.TABLE_NAME, null,
				MessageTable.MESSAGEID + "=?",
				new String[] { mAppBean.RECOMMEND_ID }, null, null, "_id asc");
		// 获取列的索引
		int id = cursor.getColumnIndex(MessageTable.ID);
		int appId = cursor.getColumnIndex(MessageTable.APPID);
		int appName = cursor.getColumnIndex(MessageTable.NAME);
		int appIcon = cursor.getColumnIndex(MessageTable.ICON);
		int downloadC = cursor.getColumnIndex(MessageTable.DOWNLOAD_COUNT);
		int appAuthor = cursor.getColumnIndex(MessageTable.AUTHOR);
		int appPack = cursor.getColumnIndex(MessageTable.PUCKAGE_NAME);
		int appVerName = cursor.getColumnIndex(MessageTable.VERSION_NAME);
		int appVer = cursor.getColumnIndex(MessageTable.VERSION_CODE);
		int appSize = cursor.getColumnIndex(MessageTable.SIZE);
		int appCat = cursor.getColumnIndex(MessageTable.CAT);
		int appUrl = cursor.getColumnIndex(MessageTable.DOWNLOAD_LINE);
		int appDesc = cursor.getColumnIndex(MessageTable.DESE);
		int screenshot = cursor.getColumnIndex(MessageTable.IMAGE_URL);
		for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
			mAppBean.ID = cursor.getString(id);
			mAppBean.APP_ID = cursor.getString(appId);
			mAppBean.APP_NAME = cursor.getString(appName);
			mAppBean.APP_ICON = cursor.getString(appIcon);
			mAppBean.DOWNLOAD_COUNT = cursor.getString(downloadC);
			mAppBean.APP_AUTHOR = cursor.getString(appAuthor);
			mAppBean.APP_PACK = cursor.getString(appPack);
			mAppBean.APP_VER_NAME = cursor.getString(appVerName);
			mAppBean.APP_VER = cursor.getInt(appVer);
			mAppBean.APP_SIZE = cursor.getString(appSize);
			mAppBean.APP_CAT = cursor.getString(appCat);
			mAppBean.APP_URL = cursor.getString(appUrl);
			mAppBean.APP_DESC = cursor.getString(appDesc);
			String[] screenshotArr = cursor.getString(screenshot).split(",");

			ScreenshotBean[] sbArr = new ScreenshotBean[screenshotArr.length];
			for (int i = 0; i < screenshotArr.length; i++) {
				// Cursor cursors = marketDB.query(ScreenshotTable.TABLE_NAME,
				// null, ScreenshotTable.ID + "=?",
				// new String[] { screenshotArr[i] }, null, null,
				// "_id asc");
				// // 获取列的索引
				// int image = cursors.getColumnIndex(ScreenshotTable.IMAGE);
				// int thumb = cursors.getColumnIndex(ScreenshotTable.THUMB);
				// for (cursors.moveToFirst(); !(cursors.isAfterLast()); cursors
				// .moveToNext()) {
				sbArr[i] = new ScreenshotBean();
				sbArr[i].IMAGE = screenshotArr[0];
				sbArr[i].THUMB = screenshotArr[0];
				// }
				// cursors.close();
			}
			mAppBean.SCREENSHOT = sbArr;
			count++;
		}
		cursor.close();
		return count;
	}

	private void getDataFromNetwork(SharedPreferences sPreferences) {
		HttpConnection hc = new HttpConnection();
		String resultJson = hc.requestService(REQS_CONFIG, new String[] {
				ConstantsTable.KEY_APPID, mAppBean.APP_ID,
				ConstantsTable.KEY_VC, ConstantsTable.NOW_VERSION,
				ConstantsTable.KEY_IMEI, ConstantsTable.IMEI });

		JSONObject person = null;
		try {
			JSONTokener jsonParser = new JSONTokener(resultJson);
			person = (JSONObject) jsonParser.nextValue();
			mAppBean.APP_NAME = person.getString("an");
			mAppBean.APP_ICON = person.getString("icon");
			mAppBean.DOWNLOAD_COUNT = person.getString("dc");
			mAppBean.APP_AUTHOR = person.getString("au");
			mAppBean.APP_PACK = person.getString("pn");
			mAppBean.APP_VER_NAME = person.getString("ver");
			mAppBean.APP_VER = person.getInt("vc");
			mAppBean.APP_SIZE = person.getString("sz");
			mAppBean.APP_CAT = person.getString("cat");
			mAppBean.APP_URL = person.getString("dl");
			mAppBean.APP_LANGUAGE = person.getString("lan");
			mAppBean.APP_DESC = person.getString("desc");
			mAppBean.APP_SCORE = person.getString("score");

			JSONArray jsonArr = person.getJSONArray("st");
			int length = jsonArr.length();
			mAppBean.SCREENSHOT = new ScreenshotBean[length];
			for (int i = 0; i < length; i++) {// 遍历JSONArray
				JSONObject oj = jsonArr.getJSONObject(i);
				ScreenshotBean sb = new ScreenshotBean();
				sb.IMAGE = oj.getString("img");
				sb.THUMB = oj.getString("timg");
				// sb.THUMB =
				// "http://coolapk.com/~/uploads/allimg/120606/2_120606120135_"
				// + (i + 1) + ".jpg";
				sb.DESC = oj.getString("desc");
				mAppBean.SCREENSHOT[i] = sb;
			}
		} catch (JSONException e) {// 如果没有新版本升级就会报这个异常
			Log.e(ConstantsTable.LOG_TAG, "AppInfoActivity json error");
			e.printStackTrace();
		}

		/**
		 * 信息存入数据库
		 */
		new Thread(new Runnable() {
			@Override
			public void run() {
				SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
				// // 1.先清除旧数据
				// // 查询表中的数据
				// Cursor cursor = marketDB
				// .query(AppInfoTable.TABLE_NAME,
				// new String[] { AppInfoTable.SCREENSHOT },
				// AppInfoTable.APP_ID + "=?",
				// new String[] { mAppBean.APP_ID }, null, null,
				// "_id asc");
				// // 获取列的索引
				// int scre = cursor.getColumnIndex(AppInfoTable.SCREENSHOT);
				// String screenshotArrStr = null;// 数据库中保存的截图表id
				// for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor
				// .moveToNext()) {
				// screenshotArrStr = cursor.getString(scre);
				// }
				// if (screenshotArrStr != null) {
				// String[] scrArr = screenshotArrStr.split(",");
				// for (int i = 0; i < scrArr.length; i++) {
				// marketDB.delete(ScreenshotTable.TABLE_NAME,
				// ScreenshotTable.ID + "=?",
				// new String[] { scrArr[i] });
				// }
				// }
				// marketDB.delete(AppInfoTable.TABLE_NAME, AppInfoTable.APP_ID
				// + "=?", new String[] { mAppBean.APP_ID });

				// 2.插入新数据
				ContentValues cv = new ContentValues();
				StringBuffer sBuffer = new StringBuffer();
				if (mAppBean.SCREENSHOT != null) {
					for (int n = 0; n < mAppBean.SCREENSHOT.length; n++) {
						ScreenshotBean sb = mAppBean.SCREENSHOT[n];
						cv.put(ScreenshotTable.IMAGE, sb.IMAGE);
						cv.put(ScreenshotTable.THUMB, sb.THUMB);
						cv.put(ScreenshotTable.DESC, sb.DESC);
						long id = marketDB.insert(ScreenshotTable.TABLE_NAME,
								null, cv);
						sBuffer.append(id + ",");
					}
				}

				ContentValues tcv = new ContentValues();
				tcv.put(AppInfoTable.APP_ID, mAppBean.APP_ID);
				tcv.put(AppInfoTable.APP_NAME, mAppBean.APP_NAME);
				tcv.put(AppInfoTable.APP_ICON, mAppBean.APP_ICON);
				tcv.put(AppInfoTable.DOWNLOAD_COUNT, mAppBean.DOWNLOAD_COUNT);
				tcv.put(AppInfoTable.APP_AUTHOR, mAppBean.APP_AUTHOR);
				tcv.put(AppInfoTable.APP_PACK, mAppBean.APP_PACK);
				tcv.put(AppInfoTable.APP_VER_NAME, mAppBean.APP_VER_NAME);
				tcv.put(AppInfoTable.APP_VER, mAppBean.APP_VER);
				tcv.put(AppInfoTable.APP_SIZE, mAppBean.APP_SIZE);
				tcv.put(AppInfoTable.APP_CAT, mAppBean.APP_CAT);
				tcv.put(AppInfoTable.APP_URL, mAppBean.APP_URL);
				tcv.put(AppInfoTable.APP_LANGUAGE, mAppBean.APP_LANGUAGE);
				tcv.put(AppInfoTable.APP_DESC, mAppBean.APP_DESC);
				tcv.put(AppInfoTable.APP_SCORE, mAppBean.APP_SCORE);
				tcv.put(AppInfoTable.SCREENSHOT, sBuffer.toString());

				marketDB.insert(AppInfoTable.TABLE_NAME, null, tcv);
			}
		}).start();

		// 保存刷新值
		SharedPreferences.Editor editor_isstop = sPreferences.edit();
		editor_isstop.putLong(APPINFO_LOGTIME, System.currentTimeMillis());
		editor_isstop.commit();
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case LOADING_DONE: {
				mAppNameTV.setText(mAppBean.APP_NAME);
				try {
					mAppSV.setPoint(Integer.valueOf(mAppBean.APP_SCORE));
				} catch (Exception e) {
					mAppSV.setPoint(0);
				}
				mAppDownloadCountTV.setText(mAppBean.DOWNLOAD_COUNT);
				mAppVersion.setText(mAppBean.APP_VER_NAME);
				mAppSize.setText(mAppBean.APP_SIZE);
				// mAppLan.setText(mAppBean.APP_LANGUAGE);
				mAppAutho.setText(mAppBean.APP_AUTHOR);
				mAppDesc.setText(mAppBean.APP_DESC);
				if (mAppBean.APP_ICON_BMP == null) {
					mIconIM.setImageResource(R.drawable.icon);
					new Thread(new Runnable() {
						@Override
						public void run() {
							File file = new File(ConstantsTable.CACHE_PATH
									+ "/" + mAppBean.APP_ID);
							Bitmap bmp = null;
							if (file.exists()) {// 如果有缓存文件
								bmp = Tools
										.getBitmapFromCache(ConstantsTable.CACHE_PATH
												+ "/" + mAppBean.APP_ID);
							} else {// 没有缓存就从网络获取
								HttpConnection hc = new HttpConnection();
								bmp = hc.getNetworkBitmap(mAppBean.APP_ICON);

								Tools.saveBmpToSd(bmp, mAppBean.APP_ID);// 保存至缓存
							}
							Drawable drawable = new BitmapDrawable(bmp);
							mAppBean.APP_ICON_BMP = drawable;
							mHandler.sendEmptyMessage(REFRESH_ICON);
						}
					}).start();
				} else {
					mIconIM.setImageDrawable(mAppBean.APP_ICON_BMP);
				}
				initScreenshot();
				dissmissProgressDialog();
				break;
			}
			case REFRESH_ICON:
				if (mAppBean.APP_ICON_BMP != null) {
					mIconIM.setImageDrawable(mAppBean.APP_ICON_BMP);
				}
				break;
			case REFRESH_LIST:
				if (mAppBean.SCREENSHOT[0].IMAGE_BMP != null
						&& mAppBean.SCREENSHOT[0].IMAGE_BMP.get() != null) {
					mAppImageView
							.setImageBitmap(mAppBean.SCREENSHOT[0].IMAGE_BMP
									.get());
				}
				break;
			default:
			}

		}
	};

	private void dissmissProgressDialog() {
		if (mLoadingDialog != null && !isFinishing()
				&& mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}

	private void initScreenshot() {
		try {
			mBlockingQueue.put(new Runnable() {
				@Override
				public void run() {
					mHandler.removeMessages(REFRESH_LIST);
					File file = new File(ConstantsTable.CACHE_PATH + "/"
							+ mAppBean.APP_ID + "_IMAGE_0");
					Bitmap bmp = null;
					if (file.exists()) {// 如果有缓存文件
						bmp = Tools
								.getBitmapFromCache(ConstantsTable.CACHE_PATH
										+ "/" + mAppBean.APP_ID + "_IMAGE_0");
					} else {// 没有缓存就从网络获取
						HttpConnection hc = new HttpConnection();
						bmp = hc.getNetworkBitmap(mAppBean.SCREENSHOT[0].IMAGE);

						Tools.saveBmpToSd(bmp, mAppBean.APP_ID + "_IMAGE_0");// 保存至缓存
					}
					SoftReference<Bitmap> sb = new SoftReference<Bitmap>(bmp);
					mAppBean.SCREENSHOT[0].IMAGE_BMP = sb;
					mHandler.sendEmptyMessageDelayed(REFRESH_LIST, REFRESH_TIME);
				}
			});
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executeDownloadBitmapThread();
	}

	public void executeDownloadBitmapThread() {
		Runnable runnable = mBlockingQueue.poll();
		if (runnable != null) {
			try {
				mExecutor.execute(runnable);
			} catch (Exception e) {
				Log.e(ConstantsTable.LOG_TAG, "拒绝执行异常AppinfoActivity");
			}
		}
	}
}
